package com.woke.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bean.UserInfo;
import com.bean.UserWallet;
import com.bean.VipLevel;
import com.bumptech.glide.Glide;
import com.example.woke.CaixintonglistActivity;
import com.example.woke.LoadActivity;
import com.example.woke.MyinfoActivity;
import com.example.woke.MyloanActivity;
import com.example.woke.MywalletActivity;
import com.example.woke.SettingActivity;
import com.example.woke.ZcailistActivity;
import com.example.woke1.MylicaiActivity;
import com.http.HttpMethods;
import com.netease.nim.uikit.GlideApp;
import com.woke.addressactivity.ExChangeActivity;
import com.woke.addressactivity.UserinfoActivity;
import com.woke.data.Datas_event2;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.wokeMy.view.Lottery.RecordBetActivity;
import com.wokeMy.view.LotteryMainActivity;
import com.wokeMy.view.RecordCreditActivity;
import com.wokeMy.view.view.RoundImageView;
import com.wokeMy.view.view.ZiqinListActivity;
import com.zhongcai.online.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.RoundingMode;
import java.text.DecimalFormat;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 我的
 *
 * @author Administrator
 */
public class UserFragment extends Fragment implements OnClickListener {

    private View layout;
    private LayoutInflater minflater;
    private TextView mTload, mTphone;
    private MyApp application;
    private TextView mTxinj, mTshou;
    private String user_money = "0.00";
    private String user_proceeds = "0.00";
    private ImageView mIjin;
    private RoundImageView mIcoin;

    private TextView mTnicename;
    private Datas_load loaded;
    private RelativeLayout relative;
    private Handler mHandler=new Handler();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        if (layout == null) {
            minflater = inflater;
            layout = minflater.inflate(R.layout.frment_user, null);
            application = (MyApp) getActivity().getApplication();
            intview();
        } else {
            ViewGroup parent = (ViewGroup) layout.getParent();
            if (parent != null) {
                parent.removeView(layout);
            }
        }
        return layout;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Datas_event2 event) {
        Log.e("UserFragment", "onEventMainThread");

        if (isVisible()) {
            onResume();
            getmywallet();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updataUserInfo(VipLevel vipLevel) {
        if (isVisible()) {
            if (getContext() != null) {
                getmywallet();  //用户升级后,更新钱包
                String registerid = JPushInterface.getRegistrationID(getContext());
                SharedPreferences sharep = getContext().getSharedPreferences("loaduser", Context.MODE_PRIVATE);

                String name = sharep.getString("name", "");
                String password = sharep.getString("password", "");
                HttpMethods.getInstance().login(mLoginObserver, name, password, registerid);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        loaded = application.getDatas_load();
        if (null != loaded) {
            mIjin.setVisibility(View.VISIBLE);
            mTphone.setText(loaded.getUser_login());
            if (null != loaded.getCom_name() && !loaded.getCom_name().equals("")) {
                mTnicename.setText(loaded.getCom_name());
            } else {
                if ("0".equals(loaded.getUser_nicename())) {

                } else {
                    mTnicename.setText(loaded.getUser_nicename());
                }
            }

            if (!TextUtils.isEmpty(loaded.getAvatar())) {
                String avatar = loaded.getAvatar();
                if (!avatar.startsWith("http")) {
                    avatar = "http://" + avatar;
                }
                Log.e("UserFragment", "Glide" + avatar);
                GlideApp.with(this)
                        .load(avatar)
                        .placeholder(R.mipmap.icn__launch_oem)
                        .error(R.mipmap.icn__launch_oem)
                        .into(mIcoin);
            }

//            String icon = loaded.icon;
//            if (!TextUtils.isEmpty(icon)) {
//                if (!icon.startsWith("http")) {
//                    icon = "http://" + icon;
//                }
//                Glide.with(this).load(icon).into(mIjin);
//            }
            Log.e("user",loaded.toString());
            switch (loaded.getUser_type()) {
                case "2":
                    mIjin.setBackgroundResource(R.mipmap.tong);
                    break;
                case "3":
                    mIjin.setBackgroundResource(R.mipmap.yin_ioc);
                    break;
                case "4":
                    mIjin.setBackgroundResource(R.mipmap.jin);
                    break;
                case "5":
                    mIjin.setBackgroundResource(R.mipmap.hhr);
                    break;
                case "6":
                    mIjin.setBackgroundResource(R.mipmap.tophhr);
                    break;
                default:
                    mIjin.setBackgroundResource(R.mipmap.tong);
                    break;
            }
            mTload.setText(loaded.vipdescribe);

            getmywallet();
        } else {
            mTload.setText("登 录  / 注 册");
            mIjin.setVisibility(View.GONE);
        }
    }

    private void getmywallet() {
        Datas_load datasLoad = application.getDatas_load();
        if (datasLoad != null) {
            String userLogin = datasLoad.getUser_login();
            if (!TextUtils.isEmpty(userLogin)) {
                HttpMethods.getInstance().userWallet(mWalletObserver, userLogin);
            }
        }
    }

    Observer<UserWallet> mWalletObserver = new Observer<UserWallet>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(UserWallet value) {
            if (value != null) {
//				String money_f = getString (R.string.user_money_f);
                Log.e("money ", value.toString());
                String money_f = getResources().getString(R.string.user_money_f3);
                DecimalFormat ddf = new DecimalFormat("0.00");
                ddf.setMaximumFractionDigits(2);
                ddf.setGroupingSize(0);
                ddf.setRoundingMode(RoundingMode.FLOOR);
                user_money = ddf.format(value.getUser_money());
                user_proceeds = ddf.format(value.getUser_proceeds());
                mTxinj.setText(String.format(money_f, user_money));
                mTshou.setText(String.format(money_f, user_proceeds));

            }
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };

    private void intview() {
        mTload = (TextView) layout.findViewById(R.id.fmuser_text_load);
        mTphone = (TextView) layout.findViewById(R.id.fmuser_text_phone);
        mTload.setOnClickListener(this);
        mTxinj = (TextView) layout.findViewById(R.id.fmuser_wallet_xianjin);
        mTshou = (TextView) layout.findViewById(R.id.fmuser_wallet_shouyi);
        mIjin = (ImageView) layout.findViewById(R.id.fmuser_image_jin);

//		if(null != application.getuserid()){
//			mTload.setText(application.getuserid());
//		}
        mTnicename = (TextView) layout.findViewById(R.id.fmuser_linear_nicename);
        layout.findViewById(R.id.fmuser_linear_list).setOnClickListener(this);
        layout.findViewById(R.id.fmuser_image_setting).setOnClickListener(this);
        mIcoin = (RoundImageView) layout.findViewById(R.id.fmuser_image_load);
        relative = (RelativeLayout) layout.findViewById(R.id.relative);
        relative.setOnClickListener(this);
//		mIcoin.setOnClickListener(this);
        layout.findViewById(R.id.fmuser_text_userinfo).setOnClickListener(this);
        layout.findViewById(R.id.fmuser_text_myloan).setOnClickListener(this);
        layout.findViewById(R.id.fmuser_mylslsl_wallet).setOnClickListener(this);
        layout.findViewById(R.id.fmuser_text_setting).setOnClickListener(this);
        layout.findViewById(R.id.fmuser_text_mysale).setOnClickListener(this);
        layout.findViewById(R.id.fmuser_text_mycaixintong).setOnClickListener(this);
        layout.findViewById(R.id.fmuser_text_mylicai).setOnClickListener(this);
        layout.findViewById(R.id.fmuser_text_myzongchou).setOnClickListener(this);
        layout.findViewById(R.id.fmuser_linear_zhilist).setOnClickListener(this);
        RoundedBitmapDrawable circularBitmapDrawable =
                RoundedBitmapDrawableFactory.create(getResources(), BitmapFactory.decodeResource(getResources(), R.mipmap.icn__launch_oem));
        circularBitmapDrawable.setCircular(true);
        mIcoin.setImageDrawable(circularBitmapDrawable);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 651 && resultCode == 658) {
            String phone = data.getStringExtra("phone");
            mTphone.setText(phone);
        } else if (requestCode == 652 && resultCode == 659) {

            Datas_load loaded2 = application.getDatas_load();
            if (loaded2 != null && !TextUtils.isEmpty(loaded2.getAvatar())) {
                String avatar = loaded2.getAvatar();
                if (!avatar.startsWith("http")) {
                    avatar = "http://" + avatar;
                }
                Log.e("UserFragment", "Glide avatar" + avatar);
                GlideApp.with(this)
                        .load(avatar)
                        .placeholder(R.mipmap.icn__launch_oem)
                        .error(R.mipmap.icn__launch_oem)
                        .into(mIcoin);
            }
        }
    }


    @Override
    public void onClick(View v) {

        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.fmuser_text_load:
            case R.id.fmuser_text_userinfo:
                if (loaded != null) {
                    intent.setClass(getActivity(), UserinfoActivity.class);
                    startActivityForResult(intent, 652);
                } else {
                    intent.setClass(getActivity(), LoadActivity.class);
                    startActivityForResult(intent, 651);
                }
                break;

            case R.id.fmuser_linear_list:
                if (loaded == null) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                } else {
                    intent.setClass(getActivity(), ZcailistActivity.class);
                    startActivity(intent);

                }
                break;

            case R.id.relative:
                if (loaded != null) {
                    intent.setClass(getActivity(), UserinfoActivity.class);
                    startActivityForResult(intent, 652);
                } else {
                    intent.setClass(getActivity(), LoadActivity.class);
                    startActivityForResult(intent, 651);
                }
                break;

            case R.id.fmuser_mylslsl_wallet:
                if (loaded == null) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                } else {
                    intent.setClass(getActivity(), MywalletActivity.class);
                    intent.putExtra("user_money", user_money);
                    intent.putExtra("user_proceeds", user_proceeds);
                    startActivity(intent);
                }
                break;

            case R.id.fmuser_image_setting:
                if (null == loaded) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                } else {
                    intent.setClass(getActivity(), MyinfoActivity.class);
                    startActivity(intent);
                }

                break;

            case R.id.fmuser_text_myloan:
                if (null == loaded) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                } else {
                    intent.setClass(getActivity(), MyloanActivity.class);
                    startActivity(intent);
                }
                break;

            case R.id.fmuser_text_setting:
                if (null == loaded) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                } else {
                    intent.setClass(getActivity(), SettingActivity.class);
                    startActivity(intent);
                }
                break;

            case R.id.fmuser_text_mylicai:
                if (null == loaded) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                } else {
                    intent.setClass(getActivity(), MylicaiActivity.class);
                    startActivity(intent);
                }

                break;

            case R.id.fmuser_text_mysale:
//			Toast.makeText(getActivity(), "功能暂未开通", Toast.LENGTH_SHORT).show();
                if (null == loaded) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                } else {
//					intent.setClass (getActivity (), ZhongjinsuoActivity.class);
                    intent.setClass(getActivity(), ExChangeActivity.class);
                    startActivity(intent);
                }
                break;

            case R.id.fmuser_text_myzongchou:
                if (null == loaded) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                } else {
//                    intent.setClass(getActivity(), MyzhongchouActivity.class);
//                    startActiviy(intent);
//                    Toast.makeText(getContext(),"暂未开通",Toast.LENGTH_SHORT).show();
                    Intent intent2 =new Intent(getContext(), RecordBetActivity.class);
                    startActivity(intent2);
                }
//			Toast.makeText(getActivity(), "������δ��ͨ", Toast.LENGTH_SHORT).show();
                break;

            case R.id.fmuser_text_mycaixintong:
                if (null == loaded) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                } else {
                    intent.setClass(getActivity(), CaixintonglistActivity.class);
                    startActivity(intent);

                }
                break;
            case R.id.fmuser_linear_zhilist:
                if (null == loaded) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                } else {
                    intent.setClass(getActivity(), ZiqinListActivity.class);
                    startActivity(intent);
                }
                break;

            default:
                break;
        }
    }


    private Observer<UserInfo> mLoginObserver = new Observer<UserInfo>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(UserInfo info) {
            if (info != null) {
                if (loaded != null) {
                    loaded.vipdescribe = info.getVipdescribe();
                    loaded.icon = info.getIcon();
                    application.setDatas_load(loaded);
                } else {
                    loaded = application.getDatas_load();
                    loaded.vipdescribe = info.getVipdescribe();
                    loaded.icon = info.getIcon();
                    application.setDatas_load(loaded);
                }
//                mHandler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        String icon = loaded.icon;
//                        if (!TextUtils.isEmpty(icon)) {
//                            if (!icon.startsWith("http")) {
//                                icon = "http://" + icon;
//                            }
//                            Glide.with(UserFragment.this).load(icon).into(mIjin);
//                        }
//
//                    }
//                },1000);
                switch (loaded.getUser_type()) {
                    case "2":
                        mIjin.setBackgroundResource(R.mipmap.tong);
                        break;
                    case "3":
                        mIjin.setBackgroundResource(R.mipmap.yin_ioc);
                        break;
                    case "4":
                        mIjin.setBackgroundResource(R.mipmap.jin);
                        break;
                    case "5":
                        mIjin.setBackgroundResource(R.mipmap.hhr);
                        break;
                    case "6":
                        mIjin.setBackgroundResource(R.mipmap.tophhr);
                        break;
                    default:
                        mIjin.setBackgroundResource(R.mipmap.tong);
                        break;
                }
                mTload.setText(loaded.vipdescribe);
            }

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };

}
